package parsers.student;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import parsers.CommonMethods;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import model.student.Direction;
import model.student.Group;

public class DirectionsParser
{	
	private Direction direction;
	
	public DirectionsParser(Direction direction) 
	{
		this.direction = direction;
	}
	
	public ArrayList<Group> parse(boolean linkWithParent) throws IOException
	{
		ArrayList<Group> groups = new ArrayList<Group>();
		
		Source source = new Source(new URL(direction.getLink()));
		List<Element> elements = source.getAllElements(HTMLElementName.A);

		for (Element element : elements)
		{
			String name = element.toString();
			if(name.contains("grupy_plan"))
			{
				List<Element> linkElements=element.getAllElements(HTMLElementName.A);
				for (Element linkElement : linkElements) 
				{
					String link = linkElement.getAttributeValue("href");
					if (link==null) 
						continue;
					
					String groupName = linkElement.getContent().getTextExtractor().toString();
					String description = groupName.substring(groupName.indexOf("("), groupName.length());
					groupName = groupName.substring(0, groupName.indexOf("(")).trim();
					
					Group group = null;
					if(linkWithParent)
					{
						group = direction.createGroup(groupName, description);
					}
					else
					{
						group = new Group(groupName, description);
					}
					group.setLink(CommonMethods.parseLink(link));
					groups.add(group);
				}
			}
		}
		
		return groups;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		Direction d = new Direction("Informatyka");
		d.setLink("file:/D:/test2.html");
		DirectionsParser gp = new DirectionsParser(d);
		ArrayList<Group> list = gp.parse(true);
		System.out.println(d);
	}*/
}
